/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Apr 14, 2012  3:21:28 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : apps.promis.in.construction
 * File Name : PaymentRequestOutgoing.java
 * TODO
 */
package apps.promis.in.construction;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import jpa.entitys.promis.common.Company;
import jpa.entitys.promis.common.CostBuildingPhase;
import jpa.entitys.promis.common.CostBuildingPhasePK;
import jpa.entitys.promis.common.CostProject;
import jpa.entitys.promis.common.CostProjectZone;
import jpa.entitys.promis.common.CostProjectZonePK;
import jpa.entitys.promis.common.PropertyType;
import jpa.entitys.promis.construction.PaymentRequestHeader;
import jpa.entitys.promis.construction.PaymentRequestHeaderPK;
import jpa.entitys.promis.construction.PaymentRequestInstallment;
import jpa.entitys.promis.construction.PaymentRequestInstallmentPK;
import jpa.entitys.promis.construction.PaymentRequestOutgoing;
import jpa.entitys.promis.construction.PaymentRequestOutgoingPK;
import jpa.entitys.promis.construction.VwSyncContract;
import jpa.entitys.promis.construction.VwSyncRequestPayment;
import jpa.entitys.synchro.staging.FiLivOutgoingpaymentInb;
import jpa.service.promis.common.CompanyServices;
import jpa.service.promis.common.CostBuildingPhaseServices;
import jpa.service.promis.common.CostProjectZoneServices;
import jpa.service.promis.common.ProjectServices;
import jpa.service.promis.common.PropertyTypeServices;
import jpa.service.promis.construction.PaymentRequestHeaderServices;
import jpa.service.promis.construction.PaymentRequestInstallmentServices;
import jpa.service.promis.construction.PaymentRequestOutgoingServices;
import jpa.service.promis.construction.VwSyncContractServices;
import jpa.service.promis.construction.VwSyncRequestPaymentServices;
import jpa.service.synchro.staging.FiLivOutgoingpaymentInbServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import promis.utility.Utilitys;
import apps.sessionFactory;

/**
 * 
 * @author Chatree Siangklom of Administrator
 * Date =Nov 13, 2013 : 2:40:01 PM 
 * CreateBy=Chatree Siangklom
 * 
 * PaymentRequestOutgoingAction
 * TODO
 */
public class PaymentRequestOutgoingAction {
	
	private static final Logger log = Logger.getLogger(PaymentRequestOutgoingAction.class);
	private EntityManager  EmPromis;
	private EntityManager  EmSynchro;

	/**
	 * 
	 * Date =Nov 13, 2013 : 2:40:07 PM 
	 * CreateBy=Chatree Siangklom
	 * PaymentRequestOutgoingAction
	 * TODO
	 * @throws Exception
	 */
	public PaymentRequestOutgoingAction() throws Exception {
		EmPromis = sessionFactory.CreateEmPromis();
		EmSynchro = sessionFactory.CreateEmSynchro();
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:40:10 PM 
	 * CreateBy=Chatree Siangklom
	 * Long
	 * TODO
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Deprecated
	private Long CalcurateMaxSeq(PaymentRequestOutgoingPK id) throws Exception {
		
		StringBuilder _strQuery = new StringBuilder();
		_strQuery.append(" SELECT  (NVL(MAX(A.SEQ_NO),0) + 1) AS MAX_SEQ, '0' AS MM  ");
		_strQuery.append(" FROM  SPL.PAYMENT_REQUEST_OUTGOING  A ");
		_strQuery.append(" WHERE A.COMPANY = ").append(Utilitys.strSql(id.getCompany()));
		_strQuery.append(" AND A.PROJECT = ").append(Utilitys.strSql(id.getProject()));
		_strQuery.append(" AND A.REQUEST_TYPE = ").append(Utilitys.strSql(id.getRequestType()));
		_strQuery.append(" AND A.REQUEST_SERIES = ").append(Utilitys.strSql(id.getRequestSeries()));
		_strQuery.append(" AND A.REQUEST_NO =  ").append(id.getRequestNo());
		_strQuery.append(" AND A.SEQ =  ").append(id.getSeq());
		log.info(CommonService.ReplaceStringToTxtDatabase(_strQuery.toString()));
		
		List<Object[]> result = (List<Object[]>)EmPromis.createNativeQuery(_strQuery.toString()).getResultList();	
		System.out.println("CalcurateMaxSeq size=" + CommonService.getSize(result));
		if(!CommonService.IsNull(result)){
			 if(result.size() > 1)
				 throw new Exception("CalcurateMaxSeq Mores then one Rec. Size="+ result.size() +" ["+ CommonService.ReplaceStringToTxtDatabase(_strQuery.toString()) +"] ");
			 
			 for (Object[] resultElement : result) {					 
				 String MAX_SEQ = CommonService.IsNullRNull(resultElement[0]); log.info("CalcurateMaxSeq MAX_SEQ=" + MAX_SEQ);
				 return Long.parseLong(MAX_SEQ);
			 }
		}else
			 return Long.parseLong("-1");
		return null;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:40:13 PM 
	 * CreateBy=Chatree Siangklom
	 * String
	 * TODO
	 * @param lst
	 * @return
	 * @throws Exception
	 */
	private String validateRString(List<FiLivOutgoingpaymentInb> lst) throws Exception {
		System.out.println("Start FiLivOutgoingpaymentInb validate ******************");
		String error = null;
		String company = null;
		String project = null;
		String buildingPhase = null;
		String zoneCode = null;
		
		List<FiLivOutgoingpaymentInb> newlst = new ArrayList<FiLivOutgoingpaymentInb>(); 
		try{	
			if(!CommonService.IsNull(lst)){
				
				for(FiLivOutgoingpaymentInb value : lst){
					if(!CommonService.IsNull(value.getSapPlantCode())){
						CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
						if(!CommonService.IsNull(costProject)){
							company = costProject.getId().getCompany();
							project = costProject.getId().getProject();							
							value.setCompanyCode(company);
							value.setProject(project);
							
							newlst.add(value);
						}
					}	
					new FiLivOutgoingpaymentInbServices(EmSynchro).Updated(newlst);
				}
				
				
				for(FiLivOutgoingpaymentInb value : lst){
					error = null; company = null; project = null; buildingPhase = null; zoneCode = null;
					
					//Company validate ********************************** 
					if(CommonService.IsNull(value.getSapCompanyCode())){					
						error = "Require field SAP Company Code !!!";
						break;
					}
					else
					{
						Company companySrv = new CompanyServices(EmPromis).findBySapCompany(value.getSapCompanyCode());
						if(companySrv == null){
							error = "Data not found SAP Company [" + value.getCompanyCode()+"]";
							break;
						}else
							company = companySrv.getCompany();
					}
					
					//Plant validate **********************************
					if(CommonService.IsNull(value.getSapPlantCode())){
						error = "Require field plant !!!";
						break;
					}
					else
					{
						CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
						if(CommonService.IsNull(costProject)){
							error = "Data not found CostProject SAP plant [" + value.getSapPlantCode()+"]";
							break;
						}else{
							project = costProject.getId().getProject();
							value.setCompanyCode(company);
							value.setProject(project);													
						}
					}
					
					//Request for Payment Document No validate **********************************
					if(CommonService.IsNull(value.getDocumentRequestNo())){
						error = "Require field Document Request No !!!";
						break;
					}
					
					//Request Type validate ************************
					if(CommonService.IsNull(value.getRequestType())){					
						error ="Require field Document Request Type !!!";
						break;
					}
					
					//Building Phase Code validate ***********************
					CostBuildingPhase CostBuildingPhaseObj = null;
					if(CommonService.IsNull(value.getBuildingPhase())){
						error = "Require field BuildingPhase !!!";
						break;
					}else{
						CostBuildingPhaseServices CostBuildingPhaseServ = new CostBuildingPhaseServices(EmPromis);
						CostBuildingPhasePK id = new CostBuildingPhasePK();
						id.setCompany(company);
						id.setProject(project);
						id.setBuildingPhase(value.getBuildingPhase());
						CostBuildingPhaseObj = CostBuildingPhaseServ.FindByKey(id);
						if(CostBuildingPhaseObj == null){
							error = "Data not found CostBuildingPhase [Company="+ company +" || Project="+ project + " ||SAP BuildingPhase=" + value.getBuildingPhase() + "]";
							break;
						}else
							buildingPhase = CostBuildingPhaseObj.getId().getBuildingPhase();
					}
										
					if(CostBuildingPhaseObj != null){
						PropertyTypeServices PropertyTypeServ = new PropertyTypeServices(EmPromis);
						PropertyType propertyType = PropertyTypeServ.findById(CostBuildingPhaseObj.getPropertyTypeCode());
						log.info("PropertyTypeCode =" + CostBuildingPhaseObj.getPropertyTypeCode());
						if(propertyType != null){
							String propertyCategory = CommonService.IsNullRString(propertyType.getPropertyCategory());
							if(propertyCategory.equals("L")){
								
								//Floor Zone for Low Rish validate ************************
								if(CommonService.IsNull(value.getZoneCode())){
									error = "Require field PhaseZone Code !!!";
									break;
								}else{
									CostProjectZoneServices CostProjectZoneServ = new CostProjectZoneServices(EmPromis);
									CostProjectZonePK id = new CostProjectZonePK();
									id.setCompany(company);
									id.setProject(project);
									id.setBuildingPhase(buildingPhase);
									id.setZoneCode(value.getZoneCode());
									
									CostProjectZone CostProjectZoneObj = CostProjectZoneServ.FindByKey(id);
									if(CostProjectZoneObj == null){
										error = "Data not found CostProjectZone [Company="+ company +" || Project="+ project + " ||BuildingPhase=" + value.getBuildingPhase() + " || SAP ZoneCode="+ value.getZoneCode() +" ]";
										break;
									}else
										zoneCode = CostProjectZoneObj.getId().getZoneCode();
								}
								
								//Unit Number validate  ****************************
								if(CommonService.IsNull(value.getUnitNumber())){					
									error = "Require field UnitNumber !!!";
									break;
								}
								
							}else if (propertyCategory.equals(""))
								error = "Data not found Property Category !!!";
								break;
						}
					}
					
					//RefDocContractNo validate  ****************************
					if(CommonService.IsNull(value.getRefDocContractNo())){					
						error = "Require field Ref DocContract No !!!";
						break;
					}
					
					//Status validate ****************************
					if(CommonService.IsNull(value.getStatus())){
						error = "Require field Status !!!";
						break;
					}else{
						if(value.getStatus().equals("A")){
							
						}else if(value.getStatus().equals("Z")){
							
						}else
						{
							error = "Data not found Status [A,Z] SAP Status:"+ value.getStatus() +" !!!";
							break;
						}
					}
					
					//SAP Internal Key validate ****************************
					if(CommonService.IsNull(value.getExtRefKey()))	{				
						error = "Require field SAP Internal Key !!!";
						break;
					}
				
					 //SAP Document No validate ****************************
					if(CommonService.IsNull(value.getExtRefNo())){
						error = "Require field SAP Document No !!!";
						break;
					}
					
					//Installment number validate **********************
					if(CommonService.IsNull(value.getInstallmentNumber())){
						error = "Require field Installment Number !!!";
						break;
					}					
				}							
				
				if(!CheckValueStatus(lst)){
					return "Error field :: status not same !!!";
				}
				
			}else
				log.warn("FiLivOutgoingpaymentInb else size=" + CommonService.getSize(lst));
			
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());	
			throw e;
		}finally
		{
			System.out.println("End FiLivOutgoingpaymentInb Validate msg ["+ CommonService.IsNullRString(error) +"] --->");
		}
		return error;
	}
	
	/**
	 * validate return value : true = pass, false = not pass
	 * @param lst
	 * @return
	 * @throws Exception
	 */
	public boolean CheckedValidattion(List<FiLivOutgoingpaymentInb> lst) throws Exception {
		System.out.println("Start FiLivOutgoingpaymentInb Validate ******************");
		boolean ispass = true;		
		try{	
						
			String msg_code = null;
			String msg_desc = null;
			String message = validateRString(lst);
			
			log.info("CheckedValidattion message=" + message);
			if(CommonService.IsNull(message)){
				msg_code = "S";
				msg_desc = "Validate Success";
				ispass = true;
			}else{
				msg_code = "E";
				msg_desc = message;
				ispass = false;
			}
			
			log.info("CheckedValidattion msg_code =" + msg_code + " || message=" + message + " || msg_desc=" + msg_desc + " || ispass=" + ispass);
			List<FiLivOutgoingpaymentInb> newValue = new ArrayList<FiLivOutgoingpaymentInb>();
			if(!CommonService.IsNull(lst)){				
				for(FiLivOutgoingpaymentInb value : lst){
					
					
					Company companySrv = new CompanyServices(EmPromis).findBySapCompany(value.getSapCompanyCode());
					if(companySrv != null)				
						value.setCompanyCode(companySrv.getCompany());
						
					CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
					if(CommonService.IsNull(costProject))
						value.setProject(costProject.getId().getProject());
					
					value.setIssync("Y");
					value.setMsgCode(msg_code);
					value.setMsgDesc(msg_desc);
					value.setMsgActResult(message);
					newValue.add(value);	
				}
			}else
				log.warn("FiLivOutgoingpaymentInbServ list size=" + CommonService.getSize(lst));
			
			//Updated to FiLivOutgoingpaymentInbServ *******************
			new FiLivOutgoingpaymentInbServices(EmSynchro).Updated(newValue);
			
			
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}finally
		{
			log.info("End FiLivOutgoingpaymentInb Validate ******************");
		}
		return ispass;
	}

	/**
	 * 
	 * @param value
	 * @param position [0-2]
	 * @return
	 * @throws Exception
	 */
	private String SubDocumentString(String value, int position) throws Exception 
	{
		try{			
			String [] temp = value.split("\\-");
			
			if(position >= 0 && position <= 2){
				System.out.println("temp 0 = " + temp[0]);
				System.out.println("temp 2 = " + temp[1]);
				System.out.println("temp 3 = " + Integer.parseInt(temp[2]));
				
				if(position == 0) 
					return temp[0];
				else if(position == 1)
					return temp[1];
				else if(position == 2)
					return temp[2];
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public boolean CheckValueStatus(List<FiLivOutgoingpaymentInb> lst) throws Exception {
		try{
			if(CommonService.getSize(lst) > 0){
			
				String status = CommonService.IsNullRString(lst.get(0).getStatus());
				for(FiLivOutgoingpaymentInb value : lst){
					if(!status.equals(value.getStatus())){
						return false;
					}
				}
				return true;		
			}			
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}
		return false;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:40:31 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param lst
	 * @throws Exception
	 */
	public void CanceledRequestForPayment(List<FiLivOutgoingpaymentInb> lst) throws Exception{
		try
		{
			if(CommonService.getSize(lst) > 0){			
				VwSyncRequestPaymentServices VwSyncRequestPaymentServ = new VwSyncRequestPaymentServices(EmPromis);
				PaymentRequestOutgoingServices PaymentRequestOutgoingServ = new PaymentRequestOutgoingServices(EmPromis);
				List<PaymentRequestOutgoing> vlauelist = new ArrayList<PaymentRequestOutgoing>();
				
				for(FiLivOutgoingpaymentInb value : lst){
					if(CommonService.IsNullRString(value.getStatus()).equals("Z")){
						
						CostProject projectobj = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
						if(projectobj != null){
																		
							String company = projectobj.getId().getCompany();
							String project = projectobj.getId().getProject();
														
							
							List<VwSyncRequestPayment> requestPayment_list = VwSyncRequestPaymentServ.findByDocUnit1(company, project, value.getBuildingPhase(), value.getZoneCode(), value.getUnitNumber(), value.getDocumentRequestNo(), CommonService.ConvertStringToBigDecimal(value.getContUnitSeq()), value.getLineInstKey());
							System.out.println("Find Request for VwSyncRequestPayment size="+ CommonService.getSize(requestPayment_list) +" || [company="+ company +" || "+ project +" || BuildingPhase="+ value.getBuildingPhase() +" || ZoneCode="+ value.getZoneCode() +" || UnitNumber="+ value.getUnitNumber() +" || DocumentRequestNo="+ value.getDocumentRequestNo() +" || Status="+ value.getStatus() +" || LineInstKey="+ value.getLineInstKey() +"]  --->");
							if(CommonService.getSize(requestPayment_list) == 1)
							{
								VwSyncRequestPayment vwSyncRequestPayment =  requestPayment_list.get(0);
								PaymentRequestOutgoingPK id = new PaymentRequestOutgoingPK();
								id.setCompany(company);
								id.setProject(project);
								id.setRequestType(vwSyncRequestPayment.getDocType());
								id.setRequestNo(vwSyncRequestPayment.getDocNo());
								id.setRequestSeries(vwSyncRequestPayment.getDocSeries());
								id.setSeq(vwSyncRequestPayment.getSeq());							
								id.setSeqNo(value.getSeqNo());
								id.setSyncExternalRefNo(value.getExtRefNo());
								
								//Check Exists Approve Status
								List<PaymentRequestOutgoing> OutGoingApproved_lst = PaymentRequestOutgoingServ.findByPB(company, project, id.getRequestNo(), id.getRequestType(), id.getRequestSeries(), id.getSeq(), id.getSeqNo(), id.getSyncExternalRefNo(), "A");
								System.out.println("company=" + company + "//project=" + project + "//RequestNo=" + id.getRequestNo() + "//RequestType=" + id.getRequestType() + "//RequestSeries=" + id.getRequestSeries() + "//getSeq=" + id.getSeq() + "//SeqNo=" + id.getSeqNo() + "//SyncExternalRefNo=" + id.getSyncExternalRefNo() + "//Status=" + "A");
								System.out.println("Find PaymentRequestOutgoing by findByPB Size=" + CommonService.getSize(OutGoingApproved_lst));
								
								if(CommonService.getSize(OutGoingApproved_lst) == 1){
									PaymentRequestOutgoing model = OutGoingApproved_lst.get(0);
									model.setStatus(value.getStatus());
									model.setPromisStagingId(value.getPromisStagingId());
									
									vlauelist.add(model);
								}
							}else
								throw new Exception("ERROR Data not found Request for Payment No : " + value.getDocumentRequestNo() + " || SAP Outgoing No : " + value.getExtRefNo() + "|| Status = " + value.getStatus());						
						}						
					}else{
						throw new Exception("Status is not Z :: Request for Payment No : " + value.getDocumentRequestNo() + " || SAP Outgoing No : " + value.getExtRefNo() + "|| Status = " + value.getStatus());
					}
				}
				
				//-----------------------------------------------------------------------------------------------------------------						
				//Check Status Aproved for Request Payment Header				
				if(CommonService.getSize(vlauelist) > 0){
					
					PaymentRequestHeaderServices paymentRequestHeaderServ = new PaymentRequestHeaderServices(this.EmPromis);
					PaymentRequestInstallmentServices PaymentRequestInstallmentServ = new PaymentRequestInstallmentServices(this.EmPromis);
					
					PaymentRequestHeaderPK paymentRequestHeaderid = new PaymentRequestHeaderPK();
					paymentRequestHeaderid.setCompany(vlauelist.get(0).getId().getCompany());
					paymentRequestHeaderid.setProject(vlauelist.get(0).getId().getProject());
					paymentRequestHeaderid.setRequestNo(vlauelist.get(0).getId().getRequestNo());
					paymentRequestHeaderid.setRequestSeries(vlauelist.get(0).getId().getRequestSeries());
					paymentRequestHeaderid.setRequestType(vlauelist.get(0).getId().getRequestType());
					
					PaymentRequestHeader paymentRequestHeader = paymentRequestHeaderServ.findById(paymentRequestHeaderid);
					
					if(paymentRequestHeader != null)
					{						
						if(CommonService.IsNullRString(paymentRequestHeader.getStatus()).equals("A") || CommonService.IsNullRString(paymentRequestHeader.getStatus()).equals("Z"))
						{
							List<PaymentRequestInstallment> PaymentRequestInstallment_lst = new ArrayList<PaymentRequestInstallment>();
							for(PaymentRequestOutgoing paymentRequestOutgoing : vlauelist)
							{																		
								PaymentRequestInstallmentPK paymentRequestInstallmentid = new PaymentRequestInstallmentPK();
								paymentRequestInstallmentid.setCompany(paymentRequestHeaderid.getCompany());
								paymentRequestInstallmentid.setProject(paymentRequestHeaderid.getProject());					
								paymentRequestInstallmentid.setRequestType(paymentRequestHeaderid.getRequestType());			
								paymentRequestInstallmentid.setRequestSeries(paymentRequestHeaderid.getRequestSeries());		
								paymentRequestInstallmentid.setRequestNo(paymentRequestHeaderid.getRequestNo());				
								paymentRequestInstallmentid.setSeq(paymentRequestOutgoing.getId().getSeq());
								
								if(CommonService.IsNull(paymentRequestOutgoing.getInstallmentSeq())) throw new Exception("Error paymentRequestOutgoing.getInstallmentSeq null !!!");
								paymentRequestInstallmentid.setInstallmentSeq(CommonService.ConvertStringToLong(paymentRequestOutgoing.getInstallmentSeq()));
								
								//System.out.println("paymentRequestOutgoing.getId().getSeq() == " + paymentRequestOutgoing.getId().getSeq());
								
								//Find Request Installment Amount
								/*
								List<PaymentRequestInstallment> paymentRequestInstallmentLst = PaymentRequestInstallmentServ.findByInstallmentNo(paymentRequestInstallmentid.getCompany(), 
																																		paymentRequestInstallmentid.getProject(), 
																																		paymentRequestInstallmentid.getRequestType(), 
																																		paymentRequestInstallmentid.getRequestSeries(), 
																																		paymentRequestInstallmentid.getRequestNo(), 
																																		paymentRequestInstallmentid.getSeq(), 
																																		CommonService.ConvertStringToBigDecimal(paymentRequestOutgoing.getInstallmentNumber()));
								*/
								PaymentRequestInstallment paymentRequestInstallment = PaymentRequestInstallmentServ.findById(paymentRequestInstallmentid);
								
								if(paymentRequestInstallment != null){
									
									//PaymentRequestInstallment paymentRequestInstallment = paymentRequestInstallmentLst.get(0);
									
									BigDecimal paymentAmount = new BigDecimal(0);
									BigDecimal paidAmount = new BigDecimal(0);
									
									if(!CommonService.IsNull(paymentRequestOutgoing.getPaymentAmount()))
										paymentAmount = paymentRequestOutgoing.getPaymentAmount();
									
									System.out.println("paymentAmount = " + paymentAmount);
									
									if(!CommonService.IsNull(paymentRequestInstallment.getPaidAmount()))
										paidAmount = paymentRequestInstallment.getPaidAmount();
									
									System.out.println("paidAmount = " + paidAmount);
									
									BigDecimal totalPaidAmount = paidAmount.subtract(paymentAmount);
									paymentRequestInstallment.setPaidAmount(totalPaidAmount);
																		
									//Check Amount not more NetPaymentAmount
									
									if(!CommonService.IsNullRString(paymentRequestInstallment.getRefType()).equals("VO")){
										if(totalPaidAmount.doubleValue() < 0){
											throw new Exception("Error (PaidAmount - PaymentAmount) < 0 value=["+ totalPaidAmount +"]");
										}
									}
									
									if(!CommonService.IsNull(paymentRequestInstallment.getPaidAmount()) && !CommonService.IsNull(paymentRequestInstallment.getNetPaymentAmount()))
									{
										if(CommonService.IsNullRString(paymentRequestInstallment.getRefType()).equals("VO")){
											if(paymentRequestInstallment.getPaidAmount().doubleValue() != paymentRequestInstallment.getNetPaymentAmount().doubleValue())
												paymentRequestInstallment.setPaymentFlag("P");
											
											if(paymentRequestInstallment.getPaidAmount().doubleValue() == paymentRequestInstallment.getNetPaymentAmount().doubleValue())
												paymentRequestInstallment.setPaymentFlag("F");
											
										}else{
											if(paymentRequestInstallment.getPaidAmount().doubleValue() < paymentRequestInstallment.getNetPaymentAmount().doubleValue())
												paymentRequestInstallment.setPaymentFlag("P");
											else if(paymentRequestInstallment.getPaidAmount().doubleValue() == paymentRequestInstallment.getNetPaymentAmount().doubleValue())
												paymentRequestInstallment.setPaymentFlag("F");
											else if(paymentRequestInstallment.getPaidAmount().doubleValue() > paymentRequestInstallment.getNetPaymentAmount().doubleValue()){
												vlauelist = null;
												PaymentRequestInstallment_lst = null;
												throw new Exception("ERROR PaidAmount > Request Installment Amount ["+ totalPaidAmount.doubleValue() + " > "+ paymentRequestInstallment.getNetPaymentAmount().doubleValue() +"]");
											}													
										}
									}
									
									//Add to List
									PaymentRequestInstallment_lst.add(paymentRequestInstallment);									
								}																
								else 
									throw new Exception("ERROR Can't Find Payment Request Installment ");
							}
							
							//Update Outgoing Payment Update Request Payment	
							//DR.TREE
							//2013-03-16
							if(CommonService.getSize(vlauelist) > 0 && CommonService.getSize(PaymentRequestInstallment_lst) > 0)
								new PaymentRequestOutgoingServices(EmPromis).InsertAndUpdate(vlauelist, PaymentRequestInstallment_lst, false);
						}
					}else{
							String temp = 	vlauelist.get(0).getId().getRequestType() + "-" + vlauelist.get(0).getId().getRequestNo() + "-" + vlauelist.get(0).getId().getRequestSeries() + "-";
											temp += Utilitys.leftPad(vlauelist.get(0).getId().getRequestNo()+"", 6, "0") + "-" + vlauelist.get(0).getId().getSeq() ;
						throw new Exception("ERROR ::: Find not found Request for Payment No : " + temp + " // SAP Outgoing No : " + lst.get(0).getExtRefNo() + "// Status = " + lst.get(0).getStatus());
					}
				}
				
				//--------------------------------------------------------------------------------------------------------------				
				try{
					
					//UPDATE IS SYNC = Y
					List<FiLivOutgoingpaymentInb> fiOutinglst = new ArrayList<FiLivOutgoingpaymentInb>();
					for(FiLivOutgoingpaymentInb obj : lst)
					{
						CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(obj.getSapPlantCode());
						if(!CommonService.IsNull(costProject))
						{
							String company = costProject.getId().getCompany();
							String project = costProject.getId().getProject();
							obj.setCompanyCode(company);
							obj.setProject(project);
						}
						
						obj.setIssync("Y");
						obj.setMsgCode("S");
						obj.setMsgDesc("Success");
						obj.setMsgActResult(null);
						fiOutinglst.add(obj);
					}				
					
					//Update Staging
					new FiLivOutgoingpaymentInbServices(EmSynchro).Updated(fiOutinglst);
					
				}catch(Exception e){
					e.printStackTrace();
					System.err.println(e.getMessage());
					log.error(e.getMessage());	
					throw e;
				}
				
			}else{
				throw new Exception("Error Can't Canceled Request For Payment List size <= 0");
			}
		}catch(Exception e){
			System.err.println(e.getMessage());
			log.error(e.getMessage());
			e.printStackTrace();
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:40:40 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO {Per transaction}
	 * @param lst
	 * @throws Exception
	 */
	public void CreatedToPromis(List<FiLivOutgoingpaymentInb> lst) throws Exception {		
		try{
			
			VwSyncContractServices VwSyncContractServ = new VwSyncContractServices(EmPromis);
			VwSyncRequestPaymentServices VwSyncRequestPaymentServ = new VwSyncRequestPaymentServices(EmPromis);
			PaymentRequestOutgoingServices PaymentRequestOutgoingServ = new PaymentRequestOutgoingServices(EmPromis);
			List<PaymentRequestOutgoing> vlauelist = new ArrayList<PaymentRequestOutgoing>();
			
			if(!CommonService.IsNull(lst)){			
				for(FiLivOutgoingpaymentInb value : lst){
					
					//SET Header
					PaymentRequestOutgoing model = null;
					
					//Find Project Master
					CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(value.getSapPlantCode());
					
					if(costProject == null) throw new Exception("Data not found Project [SAP Plant:"+ value.getSapPlantCode() +"] !!!");
					
					String company = costProject.getId().getCompany();
					String project = costProject.getId().getProject();
					String lineInstKey = CommonService.IsNullRString(value.getLineInstKey()); //value : 1||2
					
					
					//*******************************************************************
					/* 
					 * DR.TREE
					 * COMMENT 2013-04-05 
					String docRequestForPay = CommonService.IsNullRString(value.getDocumentRequestNo()); //Value : PB-1211-000023
					String [] temp = docRequestForPay.split("\\-");
					
					if(temp == null) throw new Exception("Error Document Request No is not match [value:"+ value.getDocumentRequestNo() +"] !!!");
					if(temp.length < 3) throw new Exception("Error Formatting Document Request No [value:"+ value.getDocumentRequestNo() +"] !!!");
					
					String requestType = CommonService.IsNullRString(temp[0]); //PB
					String requestSeries = CommonService.IsNullRString(temp[1]); //1211
					int requestNo = Integer.parseInt(CommonService.IsNullRZero(temp[2])); //23							
					String NewdocRequestForPay = requestType + "||" + requestSeries + "||" + requestNo;   //new String value :  PB||1211||23
																			
					String newConcatString =  company + "||" + project + "||" + NewdocRequestForPay + "||" + lineInstKey; //New Value : SP||SPVRS||PB||1211||23||1||2
					System.out.println("newConcatString=" + newConcatString);
					//*******************************************************************
					*/
										
					//Find Request for Payment (LIV Contractor)					
					List<VwSyncRequestPayment> requestPayment_list = VwSyncRequestPaymentServ.findByDocUnit0(company, project, value.getBuildingPhase(), value.getZoneCode(), value.getUnitNumber(), value.getDocumentRequestNo(), CommonService.ConvertStringToBigDecimal(value.getContUnitSeq()) , "A", lineInstKey);					
					System.out.println("Find Request for VwSyncRequestPayment size="+ CommonService.getSize(requestPayment_list) +" || [company="+ company +" || "+ project +" || BuildingPhase="+ value.getBuildingPhase() +" || ZoneCode="+ value.getZoneCode() +" || UnitNumber="+ value.getUnitNumber() +" || DocumentRequestNo="+ value.getDocumentRequestNo() +" || ContUnitSeq ="+ value.getContUnitSeq() + " || Status=A || lineInstKey="+ lineInstKey +"]  --->");
					
					VwSyncRequestPayment requestPayment = null;
					if(CommonService.getSize(requestPayment_list) == 1)
						requestPayment = requestPayment_list.get(0);
					else
						throw new Exception("Data not found Request for Payment No : " + value.getDocumentRequestNo() + " || SAP Outgoing No : " + value.getExtRefNo() + "|| Status = " + value.getStatus() + " || lineInstKey="+ lineInstKey);
						
					if(requestPayment != null)
					{
						VwSyncRequestPayment vwSyncRequestPayment =  requestPayment_list.get(0);
						PaymentRequestOutgoingPK id = new PaymentRequestOutgoingPK();
						id.setCompany(company);										//1
						id.setProject(project);										//2
						id.setRequestType(vwSyncRequestPayment.getDocType());		//3
						id.setRequestNo(vwSyncRequestPayment.getDocNo());			//4
						id.setRequestSeries(vwSyncRequestPayment.getDocSeries()); 	//5
						id.setSeq(vwSyncRequestPayment.getSeq());					//6
						
						//long seqNo = CalcurateMaxSeq(id); log.info("CalcurateMaxSeq seqNo : " + seqNo);
						//id.setSyncReplaceSeqNo(VwSyncRequestPaymentServ.GetNeqOutgoingSeqOnPromis(company));	//Dr.Tree User Oracle Triger Call Fucntion  Name : SPL.SYNC_OUGOING0_UPD_SEQNO					//7
						id.setSeqNo(value.getSeqNo());								//7
						id.setSyncExternalRefNo(value.getExtRefNo());				//8
						
						//Check Exists Approve Status
						List<PaymentRequestOutgoing> OutGoingApproved_lst = PaymentRequestOutgoingServ.findByPB(company, project, id.getRequestNo(), id.getRequestType(), id.getRequestSeries(), id.getSeq(), id.getSeqNo(), id.getSyncExternalRefNo(), "A");
						System.out.println("Find PaymentRequestOutgoing by findByPB Size=" + CommonService.getSize(OutGoingApproved_lst));
						
						if(!CommonService.IsNull(OutGoingApproved_lst)){
							model = OutGoingApproved_lst.get(0);
							String pms_status = model.getStatus();
							if(model.getStatus().equals(value.getStatus())){
								model = null;
								throw new Exception("Can't Create Outging Payment [" + value.getDocumentRequestNo() + " || PROMIS Current Transaction Status  (PMS:"+ pms_status +", SAP:" + value.getStatus() + ")]");
							}
						}else{
							if(value.getStatus().equals("A")){
								model = new PaymentRequestOutgoing();
								model.setId(id);
							}else 
								throw new Exception("Data not found Outgoing no: "+ value.getExtRefNo() + " || Request for Payment No : " + value.getDocumentRequestNo() + " || Status = " + value.getStatus());
						}
					}else
						throw new Exception("Data not found Request for Payment No : " + value.getDocumentRequestNo() + " || SAP Outgoing No : " + value.getExtRefNo() + "|| Status = " + value.getStatus());
					
					//Find Contract 					
					//List<VwSyncContract> VwSyncContractlst = VwSyncContractServ.findByDocumentNoWhtout(model.getId().getCompany() , model.getId().getProject(), value.getRefDocContractNo(), "A");
					List<VwSyncContract> VwSyncContractlst = VwSyncContractServ.findByDocumentNoWhtout1(model.getId().getCompany() , model.getId().getProject(), value.getRefDocContractNo());
					if(!CommonService.IsNull(VwSyncContractlst)){
						VwSyncContract contractObj = VwSyncContractlst.get(0);
						model.setRefSeries(contractObj.getDocSeries());
						model.setRefNo(contractObj.getDocNo());
												  
						//model.setRefSeq(contractObj.getSeq());
						//Add 2013-03-15
						//DR.TREE
						//Support 
						if(!CommonService.IsNull(value.getContUnitSeq()))
							model.setRefSeq(Long.parseLong(value.getContUnitSeq()));
						
						model.setRefType(contractObj.getDocType());
					}else
						throw new Exception("Data not found Contract No : " + value.getRefDocContractNo() + " || SAP Outgoing No : " + value.getExtRefNo() + " || Status = " + value.getStatus());
					
					//SET Detail					
					//***********************************************************
					String [] strTmp = CommonService.IsNullRString(value.getLineInstKey()).split("\\|\\|");
					if(strTmp == null) throw new Exception("Error LineInstKey is null");
					if(strTmp.length <= 0) throw new Exception("Error LineInstKey is <= 0");
					String installmentSeq = CommonService.IsNullRString(strTmp[1]);
					
					if(!CommonService.IsNull(installmentSeq))
						model.setInstallmentSeq(new BigDecimal(installmentSeq));
					//***********************************************************
					
					model.setPaymentDate(CommonService.ConvertStringToDateTime(value.getDocumentDate()));
					model.setChequeDate(CommonService.ConvertStringToDateTime(value.getChequeDate()));
					
					if(!CommonService.IsNull(value.getInstallmentNumber()))
						model.setInstallmentNumber(new BigDecimal(value.getInstallmentNumber()));
					
					if(!CommonService.IsNull(value.getPaymentAmount()))
						model.setPaymentAmount(new BigDecimal(value.getPaymentAmount()));
									
					model.setBuildingPhase(value.getBuildingPhase());
					model.setZoneCode(value.getZoneCode());
					model.setUnitNumber(value.getUnitNumber());										
					
					//Move to value as ID 2012-10-01 Dr.TRee , Meaw , Done ********** 
					//model.setSyncExternalRefNo(value.getExtRefNo());
					//********************************************************
					
					model.setSyncExternalRefKey(value.getExtRefKey());
					model.setSyncIssync("Y");
					model.setStatus(value.getStatus());
					
					//Create By 
					model.setCreatedBy(value.getCreatedBy());
					model.setCreatedOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
					model.setLastUpdBy(value.getUpdatedBy());
					model.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getUpdatedOn()));					
					if(!CommonService.IsNull(value.getUpdatedBy())){
						model.setLastUpdBy(value.getCreatedBy());
						model.setLastUpdOn(CommonService.ConvertStringToDateTime(value.getCreatedOn()));
					}
					
					model.setSyncCreatedon(model.getCreatedOn());
					model.setSyncCreatedby(model.getCreatedBy());
					
					//Add Ref PromisStagingId 
					//2013-03-14
					//Add By :: DR.TREE
					model.setPromisStagingId(value.getPromisStagingId());
					
					
					//Add LineInstKey Line of Request for payment installment
					//DR.TRREE
					//2013-04-11
					model.setLineInstKey(CommonService.IsNullRNull(value.getLineInstKey()));
					
					//PaymentRequestOutgoingServ.Inserted(model);					
					vlauelist.add(model);
				}
				
				//Insert
				//List<PaymentRequestOutgoing> PaymentRequestOutgoinglst = PaymentRequestOutgoingServ.Inserted(vlauelist);  //Dr.Tree Comment goto 
				
				//Check Status Aproved for Request Payment Header				
				if(!CommonService.IsNull(vlauelist)){
					
					PaymentRequestHeaderServices paymentRequestHeaderServ = new PaymentRequestHeaderServices(this.EmPromis);
					PaymentRequestInstallmentServices PaymentRequestInstallmentServ = new PaymentRequestInstallmentServices(this.EmPromis);
					
					PaymentRequestHeaderPK paymentRequestHeaderid = new PaymentRequestHeaderPK();
					paymentRequestHeaderid.setCompany(vlauelist.get(0).getId().getCompany());
					paymentRequestHeaderid.setProject(vlauelist.get(0).getId().getProject());
					paymentRequestHeaderid.setRequestNo(vlauelist.get(0).getId().getRequestNo());
					paymentRequestHeaderid.setRequestSeries(vlauelist.get(0).getId().getRequestSeries());
					paymentRequestHeaderid.setRequestType(vlauelist.get(0).getId().getRequestType());
					
					PaymentRequestHeader paymentRequestHeader = paymentRequestHeaderServ.findById(paymentRequestHeaderid);
					
					if(paymentRequestHeader != null)
					{						
						if(CommonService.IsNullRString(paymentRequestHeader.getStatus()).equals("A"))
						{
							List<PaymentRequestInstallment> PaymentRequestInstallment_lst = new ArrayList<PaymentRequestInstallment>();
							for(PaymentRequestOutgoing paymentRequestOutgoing : vlauelist)
							{																		
								PaymentRequestInstallmentPK paymentRequestInstallmentid = new PaymentRequestInstallmentPK();
								paymentRequestInstallmentid.setCompany(paymentRequestHeaderid.getCompany());
								paymentRequestInstallmentid.setProject(paymentRequestHeaderid.getProject());					
								paymentRequestInstallmentid.setRequestType(paymentRequestHeaderid.getRequestType());			
								paymentRequestInstallmentid.setRequestSeries(paymentRequestHeaderid.getRequestSeries());		
								paymentRequestInstallmentid.setRequestNo(paymentRequestHeaderid.getRequestNo());				
								paymentRequestInstallmentid.setSeq(paymentRequestOutgoing.getId().getSeq());
								
								if(CommonService.IsNull(paymentRequestOutgoing.getInstallmentSeq())) {
									vlauelist = null;
									PaymentRequestInstallment_lst = null;
									
									throw new Exception("Error paymentRequestOutgoing.getInstallmentSeq null !!!");
								}
								paymentRequestInstallmentid.setInstallmentSeq(CommonService.ConvertStringToLong(paymentRequestOutgoing.getInstallmentSeq()));
								
								//if(!CommonService.IsNull(paymentRequestOutgoing.getInstallmentNumber()))
								//	paymentRequestInstallmentid.setInstallmentSeq(Long.parseLong(paymentRequestOutgoing.getInstallmentNumber().toString()));	
								//log.info("paymentRequestOutgoing.getInstallmentNumber().toString() = " + paymentRequestOutgoing.getInstallmentNumber().toString());
								
								//Find Request Installment Amount
								/*
								List<PaymentRequestInstallment> paymentRequestInstallmentLst = PaymentRequestInstallmentServ.findByInstallmentNo(paymentRequestInstallmentid.getCompany(), 
																																		paymentRequestInstallmentid.getProject(), 
																																		paymentRequestInstallmentid.getRequestType(), 
																																		paymentRequestInstallmentid.getRequestSeries(), 
																																		paymentRequestInstallmentid.getRequestNo(), 
																																		paymentRequestInstallmentid.getSeq(), 
																																		CommonService.ConvertStringToBigDecimal(paymentRequestOutgoing.getInstallmentNumber()));
																																		*/
								PaymentRequestInstallment paymentRequestInstallment = PaymentRequestInstallmentServ.findById(paymentRequestInstallmentid);
								if(paymentRequestInstallment != null){
									
									BigDecimal paymentAmount = new BigDecimal(0);
									BigDecimal paidAmount = new BigDecimal(0);
									
									if(!CommonService.IsNull(paymentRequestOutgoing.getPaymentAmount()))
										paymentAmount = paymentRequestOutgoing.getPaymentAmount();							
									
									if(!CommonService.IsNull(paymentRequestInstallment.getPaidAmount()))
										paidAmount = paymentRequestInstallment.getPaidAmount();
									
									BigDecimal totalPaidAmount = paidAmount.add(paymentAmount);
									paymentRequestInstallment.setPaidAmount(totalPaidAmount);
									
									if(CommonService.getSize(lst) > 0){
										String status = CommonService.IsNullRString(lst.get(0).getStatus());										
									}
									
									//Check Amount not more NetPaymentAmount
									if(totalPaidAmount.doubleValue() > paymentRequestInstallment.getNetPaymentAmount().doubleValue()){
										vlauelist = null;
										PaymentRequestInstallment_lst = null;
										throw new Exception("Check Amount TotalPaidAmount > Request Installment Amount ["+ totalPaidAmount + " > "+ paymentRequestInstallment.getNetPaymentAmount().doubleValue() +"]");										
									}
									

									if(!CommonService.IsNull(paymentRequestInstallment.getPaidAmount()) && !CommonService.IsNull(paymentRequestInstallment.getNetPaymentAmount()))
									{
										if(CommonService.IsNullRString(paymentRequestInstallment.getRefType()).equals("VO")){
											if(paymentRequestInstallment.getPaidAmount().doubleValue() != paymentRequestInstallment.getNetPaymentAmount().doubleValue())
												paymentRequestInstallment.setPaymentFlag("P");
											
											if(paymentRequestInstallment.getPaidAmount().doubleValue() == paymentRequestInstallment.getNetPaymentAmount().doubleValue())
												paymentRequestInstallment.setPaymentFlag("F");
											
										}else{
											if(paymentRequestInstallment.getPaidAmount().doubleValue() < paymentRequestInstallment.getNetPaymentAmount().doubleValue())
												paymentRequestInstallment.setPaymentFlag("P");
											else if(paymentRequestInstallment.getPaidAmount().doubleValue() == paymentRequestInstallment.getNetPaymentAmount().doubleValue())
												paymentRequestInstallment.setPaymentFlag("F");
											else if(paymentRequestInstallment.getPaidAmount().doubleValue() > paymentRequestInstallment.getNetPaymentAmount().doubleValue()){
												vlauelist = null;
												PaymentRequestInstallment_lst = null;
												throw new Exception("ERROR PaidAmount > Request Installment Amount ["+ totalPaidAmount.doubleValue() + " > "+ paymentRequestInstallment.getNetPaymentAmount().doubleValue() +"]");
											}													
										}
									}
									
									PaymentRequestInstallment_lst.add(paymentRequestInstallment);
									
								}
								else{
									vlauelist = null;
									PaymentRequestInstallment_lst = null;
									throw new Exception("Error Can't Find Payment Request Installment !!!");
								}									
								
								/*else if(CommonService.getSize(paymentRequestInstallmentLst) > 1)
									throw new Exception("More then one Payment Request Installment size="+ CommonService.getSize(paymentRequestInstallmentLst) +"");									
								else if(CommonService.getSize(paymentRequestInstallmentLst) == 0)
									throw new Exception("Can't Find Payment Request Installment size=" + CommonService.getSize(paymentRequestInstallmentLst));
								 */
							}
							
							//Update Request Payment installment
							//PaymentRequestInstallmentServ.Updated(PaymentRequestInstallment_lst);
							
							//Insert outGoing and Update Request Payment	
							if(CommonService.getSize(vlauelist) > 0 && CommonService.getSize(PaymentRequestInstallment_lst) > 0)
								new PaymentRequestOutgoingServices(EmPromis).InsertAndUpdate(vlauelist, PaymentRequestInstallment_lst, true);
						}
					}else{
							String temp = vlauelist.get(0).getId().getRequestType() + "-" + vlauelist.get(0).getId().getRequestNo() + "-" + vlauelist.get(0).getId().getRequestSeries() + "-";
										temp += Utilitys.leftPad(vlauelist.get(0).getId().getRequestNo()+"", 6, "0") + "-" + vlauelist.get(0).getId().getSeq() ;
						throw new Exception("Find not found Request for Payment No : " + temp + " // SAP Outgoing No : " + lst.get(0).getExtRefNo() + "// Status = " + lst.get(0).getStatus());
					}
				}
				
				
				//UPDATE IS SYNC = Y
				List<FiLivOutgoingpaymentInb> fiOutinglst = new ArrayList<FiLivOutgoingpaymentInb>();
				for(FiLivOutgoingpaymentInb obj : lst)
				{
					CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(obj.getSapPlantCode());
					if(!CommonService.IsNull(costProject))
					{
						String company = costProject.getId().getCompany();
						String project = costProject.getId().getProject();
						obj.setCompanyCode(company);
						obj.setProject(project);
					}
					
					obj.setIssync("Y");
					obj.setMsgCode("S");
					obj.setMsgDesc("Success");
					obj.setMsgActResult(null);
					fiOutinglst.add(obj);
				}
				
				new FiLivOutgoingpaymentInbServices(EmSynchro).Updated(fiOutinglst);
				
			}
		}catch(Exception e)
		{
			try{
				if(!CommonService.IsNull(lst))
				{
					List<FiLivOutgoingpaymentInb> fiOutinglst = new ArrayList<FiLivOutgoingpaymentInb>();
					for(FiLivOutgoingpaymentInb obj : lst)
					{
						obj.setIssync("Y");
						obj.setMsgCode("E");
						obj.setMsgDesc(CommonService.CutString(e.getMessage(), 3500));
						obj.setMsgActResult(CommonService.CutString(e.getMessage(), 3500));
						
						fiOutinglst.add(obj);
					}
					new FiLivOutgoingpaymentInbServices(EmSynchro).Updated(fiOutinglst);
				}	
			}catch(Exception ex){
				log.error(ex.getMessage());
				System.err.println(ex.getMessage());
				throw ex;
			}

			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:40:56 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param sapPlantCode
	 * @param requestNo
	 * @param status
	 * @param instanceNo
	 * @throws Exception
	 */
	private void Start(String sapPlantCode, String requestNo, String status, String instanceNo) throws Exception {	
		try
		{					
			List<FiLivOutgoingpaymentInb> lst = new FiLivOutgoingpaymentInbServices(EmSynchro).findByRequestNo(sapPlantCode, requestNo, status, instanceNo);
			
			if(!CommonService.IsNull(lst)){
				System.out.println("Start Create Data to Staging sapPlantCode : " + sapPlantCode + " || requestNo : " + requestNo + " || status : " + status);
				CreatedToPromis(lst);
			}else
				System.out.println("Found not found record sapPlantCode : " + sapPlantCode + " || requestNo : " + requestNo + " || status : " + status);
			 
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * Re Run Order by Asc 
	 * @throws Exception
	 */
	private void ReRunAll() throws Exception{
		try{
			StringBuilder _strQuery = new StringBuilder();
			_strQuery.append(" SELECT  EXT_REF_NO,INSTANCE_NO "); 
			_strQuery.append(" FROM FI_LIV_OUTGOINGPAYMENT_INB ");		
			_strQuery.append(" WHERE ISSYNC = 'N' ");		
			_strQuery.append(" GROUP BY EXT_REF_NO,INSTANCE_NO ORDER BY EXT_REF_NO ASC ,INSTANCE_NO ASC ");
			System.out.println(_strQuery);
			
			List<Object[]> result = (List<Object[]>)EmSynchro.createNativeQuery(_strQuery.toString()).getResultList();	
			System.out.println("Group FI_LIV_OUTGOINGPAYMENT_INB size=" + CommonService.getSize(result));
			if(!CommonService.IsNull(result)){
				for (Object[] resultElement : result) {					 
					 String EXT_REF_NO = CommonService.IsNullRNull(resultElement[0]);
					 String INSTANCE_NO = CommonService.IsNullRNull(resultElement[1]);
					 
					 List<FiLivOutgoingpaymentInb> lst = new FiLivOutgoingpaymentInbServices(EmSynchro).findBySAPDocumentNo(INSTANCE_NO, EXT_REF_NO, "N");
					 System.out.println("FiLivOutgoingpaymentInb List size=" + CommonService.getSize(lst));
					 try{
						 
						 boolean isvalidate = CheckedValidattion(lst);			
						 System.out.println("Is Aalidate=" + isvalidate);
						 
						 if(isvalidate)
							 CreatedToPromis(lst);
						 
					 }catch(Exception e){
						log.error(e.getMessage());
						System.err.println(e.getMessage());
					 }					 					
				 }
			}
		}catch(Exception e){
			log.error(e);
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:00 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @throws Exception
	 */
	private void Start() throws Exception {		
		 try{
			 
			 //FiLivOutgoingpaymentInbServices  FiLivOutgoingpaymentInbServ = new FiLivOutgoingpaymentInbServices(EmSynchro);			 
			 //String sapPlantCode = "1062";
			 //String requestNo = "PB-1209-000016";
			 //String status = "A";
			 
			 //List<FiLivOutgoingpaymentInb> lst = FiLivOutgoingpaymentInbServ.findByRequestNo(sapPlantCode, requestNo, status, "10000000000001066160");
			 //List<FiLivOutgoingpaymentInb> lst = new FiLivOutgoingpaymentInbServices(EmSynchro).findByInstanceNo1("10000000000001068822","N");
			 List<FiLivOutgoingpaymentInb> lst = new FiLivOutgoingpaymentInbServices(EmSynchro).findBySAPDocumentNo("10000000000002054986", "1000-6300004009-2012", "Y");
			 System.out.println("FiLivOutgoingpaymentInb List size=" + CommonService.getSize(lst));
			 
			 boolean isvalidate = CheckedValidattion(lst);			
			 System.out.println("Is Aalidate=" + isvalidate);
			 
			 if(isvalidate)
			 {
				 String status = CommonService.IsNullRString(lst.get(0).getStatus());
					if(status.equals("A")){
						//CREATE TO PROMIS
						CreatedToPromis(lst);
					}else if(status.equals("Z")){
						//CALCEN TO PROMIS
						CanceledRequestForPayment(lst);
					}
			 }
			 
		 }catch(Exception e)
		 {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		 }
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:03 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 */
	private void UpdateOutgoingProject(){
		try{
			//UPDATE IS SYNC = Y
			List<FiLivOutgoingpaymentInb> fiOutinglst = new ArrayList<FiLivOutgoingpaymentInb>();
			FiLivOutgoingpaymentInbServices objServ = new FiLivOutgoingpaymentInbServices(EmSynchro);
			List<FiLivOutgoingpaymentInb> lst = objServ.findAll();
			
			if(CommonService.getSize(lst) > 0){
				for(FiLivOutgoingpaymentInb obj : lst)
				{
					CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(obj.getSapPlantCode());
					if(!CommonService.IsNull(costProject))
					{
						String company = costProject.getId().getCompany();
						String project = costProject.getId().getProject();
						obj.setCompanyCode(company);
						obj.setProject(project);
					}						
					fiOutinglst.add(obj);
				}
				
				new FiLivOutgoingpaymentInbServices(EmSynchro).Updated(fiOutinglst);
			}			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:06 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @throws Exception
	 */
	public void Re_RunAll() throws Exception {
		try{
			StringBuffer _strQuery = new StringBuffer();			
			_strQuery.append(" Select ");
			_strQuery.append(" SAP_PLANT_CODE, EXT_REF_NO, INSTANCE_NO, STATUS, ISSYNC ");
			_strQuery.append(" From synchro.FI_LIV_OUTGOINGPAYMENT_INB ");
			_strQuery.append(" Group by SAP_PLANT_CODE,EXT_REF_NO, INSTANCE_NO, STATUS, ISSYNC ");
			_strQuery.append(" Order by SAP_PLANT_CODE asc, EXT_REF_NO asc ,INSTANCE_NO asc, STATUS asc, ISSYNC asc ");    
			
			List<Object[]> result = (List<Object[]>)EmSynchro.createNativeQuery(_strQuery.toString()).getResultList();	
			System.out.println("query size=" + CommonService.getSize(result));
			if(!CommonService.IsNull(result)){
				int i = 0;
				for (Object[] resultElement : result) {					 
					 String SAP_PLANT_CODE = CommonService.IsNullRNull(resultElement[0]);
					 String EXT_REF_NO = CommonService.IsNullRNull(resultElement[1]);
					 String INSTANCE_NO = CommonService.IsNullRNull(resultElement[2]);
					 String STATUS = CommonService.IsNullRNull(resultElement[3]);
					 String ISSYNC = CommonService.IsNullRNull(resultElement[4]);
					 
					 List<FiLivOutgoingpaymentInb> lst = new FiLivOutgoingpaymentInbServices(EmSynchro).findBySAPDocumentNo(SAP_PLANT_CODE, INSTANCE_NO, EXT_REF_NO, ISSYNC);					 
					 boolean isvalidate = CheckedValidattion(lst);					 
					 i++;
					 System.out.println(i + ".SAP_PLANT_CODE:"+ SAP_PLANT_CODE +"//EXT_REF_NO:"+EXT_REF_NO+"//INSTANCE_NO:"+INSTANCE_NO+"//STATUS:"+STATUS+"//ISSYNC:"+ISSYNC+"//Size:"+CommonService.getSize(lst)+" Is Aalidate=" + isvalidate);
					 
					 /*
					 int ix = 0;
					 List<FiLivOutgoingpaymentInb> newlst = new ArrayList<FiLivOutgoingpaymentInb>(); 
					 if(CommonService.getSize(lst) > 0){
						 for(FiLivOutgoingpaymentInb value : lst){
							 ix++;
							 value.setSeqNo(ix);
							 newlst.add(value);
						 }
						 new FiLivOutgoingpaymentInbServices(EmSynchro).Updated(newlst);
					 }
					 */
					 
					 if(isvalidate)
					 {
						 try{
							 String status = CommonService.IsNullRString(lst.get(0).getStatus());
							 if(status.equals("A")){
									//CREATE TO PROMIS
									CreatedToPromis(lst);
								}else if(status.equals("Z")){
									//CALCEN TO PROMIS
									CanceledRequestForPayment(lst);
								}
						 }catch(Exception e){
							 System.err.println(e.getMessage());
						 }
					 }
					 
					 
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
		}
	}

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		try{
//			
//			 new PaymentRequestOutgoingAction().Start();
//			//new PaymentRequestOutgoingAction().Re_RunAll();
//			
//		}catch(Exception e)
//		{
//			log.error(e.getMessage());
//			System.err.println(e.getMessage());
//		}
//
//	}

}
